<template>
  <div>
    <BreakSpace label="查询条件" :containerStyle="{ marginBottom: '10px' }" />
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="changeHandle" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>
    <BreakSpace label="查询列表" :containerStyle="{ marginBottom: '10px' }" />
    <!--<FilterTable-->
    <!--ref="table"-->
    <!--height="300"-->
    <!--:isColumnFilter="false"-->
    <!--:columns="columns"-->
    <!--:fetchapi="fetchApi"-->
    <!--:params="fetchParams"-->
    <!--:datakey="'records'"-->
    <!--:uidkey="'optionCode'"-->
    <!--:defaultSelections="selectedRow"-->
    <!--:onSyncTableData="tableChangeFun"-->
    <!--:onRowSelectChange="selectChangeHandle"-->
    <!--:onPageChange="handleTablePageChange"-->
    <!--:onColumnsChange="columns => (this.columns = columns)"-->
  <!--/>-->
    <FilterTable
      ref="table"
      height="300"
      :isColumnFilter="false"
      :columns="columns"
      :uidkey="'optionCode'"
      :isMemoryPagination="isMemoryPagination"
      :dataSource="tableModelList"
      :defaultSelections="selectedRow"
      :onSyncTableData="tableChangeFun"
      :onRowSelectChange="selectChangeHandle"
      :onPageChange="handleTablePageChange"
      :onSelectAll="selectAll"
      :onColumnsChange="columns => (this.columns = columns)"
    />
    <!--<BreakSpace label="已选清单" :containerStyle="{ marginBottom: '10px' }" />-->
    <!--<FilterTable ref="tables" height="auto" :isColumnFilter="false" :isSelectColumn="false" :columns="columns1" :dataSource="tableList" :onColumnsChange="columns => (this.columns1 = columns)">-->
    <!--</FilterTable>-->
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDrawer(1)">关 闭</el-button>
      <el-button @click="closeDrawer(2)" type="primary">确 定</el-button>
    </div>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { queryOptionsList,queryOptionsAllList } from '@/api/omFinance/PriceDiscountManage/DiscountStrategyMaintain';
import { vehicleConfiguration } from '@/api/omFinance';
import { arrayObjDeWeight } from '@/utils';

export default {
  mixins: [dictionary],
  props: ['rowData'],

  data() {
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      columns1: this.createdTable1(),
      // fetchApi: queryOptionsList,
      fetchParams: {},
      selectedRow: [], // 选中的行项目
      totalArrList: [], // 选中的打印项目
      pageSelectRows: [], // 当前页选中的行项(过滤取消勾选项用)
      tableList: [],
      tableModelList:[],
      table:{},
      isMemoryPagination:true,
      isSelect:false,
      isFirst:true,
      isFirstSize:0,
      isSearchSize:0,
      map:new Map(),
      cachesSelectArr:[]

    };
  },
  mounted() {
    this.table=this.$refs.table.$refs.pageTable
    this.getList();
    // this.tables = this.$refs.tables.$refs.pageTable;
    this.totalArrList = this.rowData; // 选中的打印项目
    if(this.rowData.length>0){
      this.rowData.map(x=>this.map.set(x.optionCode,x))
      console.log(this.map, 'this.map');
    }

    this.getModelAllList(true);
  },
  methods: {
    selectAll(rowsData){
      if (!this.isSelect) {
        let rows=this.table.originData;
        rows.forEach(row => {
          this.table.toggleSelectionHandle(row, true)
        });
      } else {
        this.table.clearSelectionHandle();
      }
      this.isSelect=!this.isSelect
    },
    async getModelAllList(isFirst){
      this.table.START_LOADING();
      // let res=await queryOptionsList({currentPage:1,pageSize:22,pageNum:22,limit:22,current:1,size:22});
     let res= await queryOptionsAllList(this.fetchParams)
      if (res.resultCode == 200) {
        this.table.STOP_LOADING();
        this.isFirst=isFirst
        this.tableModelList= res.data;
        if(isFirst){
          this.isFirstSize=res.data.length
          this.isSearchSize=res.data.length
        }else {
          this.table.toFirstPage()
          this.isSearchSize=res.data.length
        }
        // this.tableModelList= res.data.records;
      }
    },
    async getList() {
      let res = await vehicleConfiguration(0, { isUnlimited: 10041001 });
      this.topFilterList.find(item => item.fieldName === 'vehicleInfo').itemList = res.data;
    },
    // async querySeriess() {
    //   const res = await querySeriessList();
    //   if (res.resultCode == 200) {
    //     res.data.map(x => {
    //       this.topFilterList.find(item => item.fieldName == 'seriesId').itemList.push({ text: x.seriesName, value: x.seriesId });
    //     });
    //   }
    // },
    // async queryModels(val) {
    //   this.topFilterList.find(item => item.fieldName == 'modelId').initialValue = '';
    //   this.topFilterList.find(item => item.fieldName == 'modelId').itemList = [];
    //   if (!val) return;
    //   let param = {
    //     seriesId: val
    //   };
    //   const res = await queryModelsList(param);
    //   if (res.resultCode == 200) {
    //     res.data.map(x => {
    //       this.topFilterList.find(item => item.fieldName == 'modelId').itemList.push({ text: x.modelName, value: x.modelId });
    //     });
    //   }
    // },
    // async queryPackages(val) {
    //   this.topFilterList.find(item => item.fieldName == 'packageId').initialValue = '';
    //   this.topFilterList.find(item => item.fieldName == 'packageId').itemList = [];
    //   if (!val) return;
    //   let param = {
    //     seriesId: val
    //   };
    //   const res = await queryPackagesList(param);
    //   if (res.resultCode == 200) {
    //     res.data.map(x => {
    //       this.topFilterList.find(item => item.fieldName == 'packageId').itemList.push({ text: x.configName, value: x.packageId });
    //     });
    //   }
    // },

    // table数据变化
    tableChangeFun(val) {
      //页面数据变化重新赋值选中行项
      let select=[];
       val.map(item =>{
        this.map.forEach((v,k)=>{
          if(k== item.optionCode){
            select.push(item);
          }
        })
      })
      this.selectedRow=select
      // this.selectedRow = val.filter(item => this.totalArrList.find(x => x.optionCode == item.optionCode));
      console.log(this.selectedRow, '页面数据变化重新赋值选中行项');
    },
    // table页码变化
    handleTablePageChange(e) {
      this.pageSelectRows = [];
    },
    // table行项选中变化
    selectChangeHandle(e) {e
      if(!this.isFirst && e.length==0){
        this.isFirst=true
        console.log('点击了搜索0');
        this.map.forEach((v,k)=>{
          console.log(k, 'map.forEach==k');
          console.log(v, 'map.forEach==v');
          let row= this.table.originData.find(x=>x.optionCode == k)
          if(row){
            this.table.toggleSelectionHandle(row, true)
          }
        })
        //this.tableList = this.totalArrList;
        console.log(this.map, '点击了搜索1');

      }else {
        if(e.length>0){
          // let arr=[]
          // this.map.forEach((v,k)=>{
          //   arr.push(v)
          // })
          // let total=[...arr,...e]
          // arrayObjDeWeight(total, 'optionCode')
          e.map(x=>{
            this.map.set(x.optionCode,x)
          })
        }else {
          if(this.isFirstSize==this.isSearchSize) {
            this.map.clear()
          }else {
            this.cachesSelectArr.map(x=>{
              this.map.delete(x.optionCode)
            })
          }
        }
        this.cachesSelectArr=e;

      }
      console.log(this.map, '返回前一页的map');
    },
    changeHandle(val) {
      this.fetchParams = Object.assign({}, this.fetchParams, val);
      this.getModelAllList(false);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    closeDrawer(type) {
      if (type == 1) {
        return this.$emit('close', false);
      }
      if (type == 2) {
        console.log("map==",...this.map);
        this.map.forEach((v,k)=>{
          this.tableList.push(v)
        })
       return this.$emit('close', false, this.tableList);
      }
    },
    delFun(data) {
      // this.tables.EXECUTE_DELETE([data]);
    },
    createdFrom() {
      return [
        {
          type: 'INPUT_CASCADER',
          label: '车型选择',
          fieldName: 'vehicleInfo',
          placeholder: '请选择',
          options: { titles: ['品牌', '车系', '车型', '配置', '选装', '颜色'] },
          itemList: []
        },
        // {
        //   type: 'SELECT',
        //   label: '车系名称',
        //   fieldName: 'seriesId',
        //   placeholder: '请选择',
        //   itemList: [],
        //   change: val => {
        //     this.queryModels(val);
        //     this.queryPackages(val);
        //   }
        // },
        // {
        //   type: 'SELECT',
        //   label: '车型名称',
        //   fieldName: 'modelId',
        //   placeholder: '请选择',
        //   itemList: []
        // },
        // {
        //   type: 'SELECT',
        //   label: '配置名称',
        //   fieldName: 'packageId',
        //   placeholder: '请选择',
        //   itemList: []
        // },
        {
          type: 'INPUT',
          label: '选装代码',
          fieldName: 'optionCode',
          placeholder: '请输入12位编码'
        },
        {
          type: 'INPUT',
          label: '选装名称',
          fieldName: 'optionName',
          placeholder: '请输入'
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '选装代码',
          dataIndex: 'optionCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '选装名称',
          dataIndex: 'optionName',
          align: 'center',
          width: 250,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '品牌名称',
          dataIndex: 'brandName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配置名称',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '市场指导价',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    createdTable1() {
      return [
        // {
        //   title: '序号',
        //   dataIndex: 'index',
        //   width: 80,
        //   sorter: true,
        //   fixed: 'left',
        //   render: props => {
        //     return <span>{props.row.index + 1}</span>;
        //   }
        // },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 70,
          fixed: 'left',
          render: props => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.delFun(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '选装代码',
          dataIndex: 'optionCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '选装名称',
          dataIndex: 'optionName',
          align: 'center',
          width: 250,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '品牌名称',
          dataIndex: 'brandName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '车型名称',
          dataIndex: 'modelName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配置名称',
          dataIndex: 'configName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '市场指导价',
          dataIndex: 'optionName',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    }
  }
};
</script>
